from AipSpeech import aip_speech_client
import wave, pyaudio, io
from pydub import AudioSegment
from pydub.playback import play


# 获取百度合成语音的二进制文件
def get_baidu_source(text,per):
    client = aip_speech_client.get_baidu_client();
    if(not per):
        per = 4
    result = client.synthesis(text, 'zh', 1, {
        'vol': 5,
        'per': per,
    })
    return result;


# 将mp3写入文件
def save_mp3_file(text, per):
    source_result = get_baidu_source(text, per)
    if not isinstance(source_result, dict):
        with open('auido.mp3', 'wb') as f:
            f.write(source_result);


def from_mp3_to_wav(path,fileName):
    AudioSegment.from_mp3(path).export(fileName+".wav", format="wav")


def play_from_file_by_pyaudio(filePath):
    #### 需要安装libav||ffmpeg 具体看github
    ## 只读方式打开wav文件（可以使用pydub转）
    wf = wave.open(filePath, 'rb')
    p = pyaudio.PyAudio()
    # 打开数据流
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    # 定义数据流块
    CHUNK = 1024
    # 读取数据
    data = wf.readframes(CHUNK)
    # 播放
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    # 停止数据流
    stream.stop_stream()
    stream.close()
    # 关闭 PyAudio
    p.terminate()


def play_by_text(text, per):
    ## pydub
    # song = AudioSegment.from_mp3("auido.mp3").export("audio.wav", format="wav")
    song = AudioSegment.from_mp3(io.BytesIO(get_baidu_source(text, per)))
    # song = AudioSegment.from_mp3("auido.mp3")
    play(song);